package cn.com.egova.materialdesignexample.recyclerview;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.com.egova.materialdesignexample.R;

/**
 * Created by yuanchao on 2017/4/8.
 */

public class StaggeredAdapter extends RecyclerView.Adapter<StaggeredAdapter.ViewHolder>{
    private List<String> mDataSet;
    private int orientation;
    private List<Integer> widthOrHeights;  //水平瀑布流布局则为宽度集合,垂直瀑布流布局则为高度集合.
    public StaggeredAdapter(List<String> data,int orientation){
        this.mDataSet = data;
        this.orientation = orientation;
        this.widthOrHeights = new ArrayList<>();

        for(int i=0;i<mDataSet.size();i++){
            widthOrHeights.add( (int) (120 + Math.random() * 300));    //Math.random()的取值范围为:0.0~1.0
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview,parent,false);
        StaggeredAdapter.ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        //重新设置布局参数.
        ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
        if(orientation==1){
            layoutParams.width = widthOrHeights.get(position);
        }else{
            layoutParams.height = widthOrHeights.get(position);
        }
        holder.itemView.setLayoutParams(layoutParams);
        holder.tv.setText(mDataSet.get(position));



    }

    @Override
    public int getItemCount() {
        return mDataSet.size();
    }


    //增加数据
    public void addData(int position){
        mDataSet.add(position,"Add");
        notifyItemInserted(position);
    }

    //删除数据
    public void removeData(int position){
        mDataSet.remove(position);
        notifyItemRemoved(position);
    }

    //改变数据
    public void changeData(int position){
        mDataSet.set(position,"Change");
        notifyItemChanged(position);
    }


    class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv;
        public ViewHolder(View itemView) {
            super(itemView);
            tv = (TextView) itemView.findViewById(R.id.tv_num);
        }
    }
}
